﻿namespace IndicatorsTest.Utils
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.IO;
	using System.Globalization;

	using StockSharp.Algo.Candles;

	class TextData
    {
		/// <summary>
		/// Номер строки в текстовом файле.
		/// </summary>
		public int Line { get; set; }

		/// <summary>
		/// Данные о цене.
		/// </summary>
		public Candle Candle { get; set; }

		/// <summary>
		/// Основное значение индикатора.
		/// </summary>
		public decimal Value { get; set; }

		/// <summary>
		/// Дополнительные значения индикатора.
		/// </summary>
		public decimal Value2 { get; set; }

		/// <summary>
		/// Дополнительные значения индикатора.
		/// </summary>
		public decimal Value3 { get; set; }

		/// <summary>
		/// Дополнительные значения индикатора.
		/// </summary>
		public decimal Value4 { get; set; }
    }

    static class TextDataReader
    {
		public static IEnumerable<TextData> ReadFromFile(string path, char delimiter)
        {
            var lineNumber = 0;

            return File.ReadAllLines(path).Where(line => !line.Substring(0,1).Equals("#")).Select(line =>
            {
				var parts = line.Split(delimiter);

				return new TextData
				{
                    Line = ++lineNumber,
                    Candle = new TimeFrameCandle
                    {
                        OpenPrice = ReadDecimal(parts[0]),
						HighPrice = ReadDecimal(parts[1]),
						LowPrice = ReadDecimal(parts[2]),
                        ClosePrice = ReadDecimal(parts[3]),
                        TotalVolume = Convert.ToInt32(parts[4]),
                    },
					Value = ReadDecimal(parts[5]),
					Value2 = parts.Count() > 6 ? ReadDecimal(parts[6]) : 0,
					Value3 = parts.Count() > 7 ?ReadDecimal(parts[7]) : 0,
					Value4 = parts.Count() > 8 ? ReadDecimal(parts[8]) : 0,
                };
            });
        }

		/// <summary>
		/// Reads the decimal taking into account different styles of the separator.
		/// </summary>
		/// <param name="value">The string to be parsed.</param>
		/// <param name="defaultValue">The default value to be returned on errors.</param>
		/// <returns>The decimal value of the parsed string.</returns>
		public static Decimal ReadDecimal(string value, Decimal defaultValue = 0)
		{
			Decimal result;

			// Try parsing in the current culture
			if (! Decimal.TryParse(value, NumberStyles.Any, CultureInfo.CurrentCulture, out result) &&
				// Then try in US english
				! Decimal.TryParse(value, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out result) &&
				// Then in neutral language
				! Decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out result))
			{
				result = defaultValue;
			}

			return result;
		}

    }
}
